package net.kazed.nextaction.tools;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.Task;

public class SynchronizeActivity extends ListActivity {

   private TextView numberOfTasksText;
   private Button button;
   
   private Cursor taskCursor;

	@Override
    public void onCreate(Bundle icicle) {
      setContentView(R.layout.purge_task_list);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
      
      numberOfTasksText = (TextView) findViewById(R.id.number_of_tasks);
      
      button = (Button) findViewById(R.id.purge_button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SynchronizeActivity.this);
            builder.setTitle(R.string.tools_purge_alert_title).setMessage(R.string.tools_purge_alert_message)
               .setIcon(android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                     String where = Task.COMPLETE + " = ?";
                     String[] selectionArgs = new String[] {"1"};
                     int count = getContentResolver().delete(Task.CONTENT_URI, where, selectionArgs);
                     Log.i("purge", "count: " + count);
                     taskCursor.requery();
                     populateView();
                  }
            });
            builder.setNegativeButton(R.string.alert_no, null);
            builder.show();
         }
      });

      taskCursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(),
            Task.COMPLETE + " = ?", new String[] {"1"},
            Task.CREATED_DATE + " ASC");
      setListAdapter(new SimpleCursorAdapter(this, R.layout.task_list_item_view, taskCursor,
            new String[] {Task.DESCRIPTION}, new int[] {R.id.description}));

      super.onCreate(icicle);
	}
	
	@Override
	protected void onResume() {
	   
      populateView();

		super.onResume();
	}

	/**
	 * Populate view.
	 */
   private void populateView() {
      int taskCount = taskCursor.getCount();
      numberOfTasksText.setText(Integer.toString(taskCount));
   }

}
